package cn.szzsi.common.model;

import cn.szzsi.common.bean.HtmlConfig;
import cn.szzsi.common.bean.ProductImage;
import cn.szzsi.common.controller.BaseController;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.SerialNumberUtil;
import cn.szzsi.common.kit.SystemConfigUtil;
import cn.szzsi.common.kit.TemplateConfigUtil;
import cn.szzsi.common.model.base.BaseProduct;
import cn.szzsi.service.ProductImageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;

/**
 * 实体类 - 商品
 */
public class Product extends BaseProduct<Product> {

    private static final long serialVersionUID = -8178061660099975236L;

    public static final Product dao = new Product().dao();

    public static final int MAX_BEST_PRODUCT_LIST_COUNT = 20;// 精品商品列表最大商品数
    public static final int MAX_NEW_PRODUCT_LIST_COUNT = 20;// 新品商品列表最大商品数
    public static final int MAX_HOT_PRODUCT_LIST_COUNT = 20;// 热销商品列表最大商品数
    public static final int DEFAULT_PRODUCT_LIST_PAGE_SIZE = 12;// 商品列表默认每页显示数


    // 重量单位（克、千克、吨）
    public enum WeightUnit {
        g, kg, t
    }

    // 商品属性存储
    private Map<String, String> productAttributeMapStore = new HashMap<String, String>();
    private ProductImageService productImageService = new ProductImageService();

    //对一些参数进行初始化，并加入到实体属性中
    public void initParams() {
        //规格名称
        String vs = this.getStr("specificationvalues");
        if (StrKit.notBlank(vs)) {
            List<Record> lists = Db.find("select name from mall_specification_value where id in ('" + StringUtils.replace(StringUtils.removeEnd(vs, ","), ",", "','") + "')");
            String valuenames = "";
            if (lists != null && lists.size() > 0) {
                for (Record r : lists) {
                    valuenames += r.getStr("name") + " ";
                }
                this.put("valuenames", valuenames);
            }
        }
    }

    public static String getSpecificationvaluesAll(Product product) {
        String valuenames = "";
        if (product != null) {
            valuenames = product.getSpecificationValues();
        }
        return valuenames;
    }

    /**
     * 根据分页对象搜索产品
     *
     * @return 分页对象
     */
    public Page<Product> search(int pageNumber, int pageSize, String keyword, String orderBy, BaseController.OrderType orderType) {
        String select = "select * ";
        String sqlExceptSelect = " from mall_product where isMarketable = true ";

        if (StrKit.notBlank(keyword)) {
            sqlExceptSelect += " and name like '%" + keyword + "%'";
        }

        if (StrKit.notBlank(orderBy) && StrKit.notBlank(orderType.name())) {
            sqlExceptSelect += " order by " + orderBy + " " + orderType;
        }

        Page<Product> pager = dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
        return pager;
    }

    /**
     * 根据分页对象搜索商户产品
     *
     * @return 分页对象
     */
    public Page<Product> businessSearch(String uid, int pageNumber, int pageSize, String keyword, String orderBy, BaseController.OrderType orderType) {
        String select = "select * ";
        String sqlExceptSelect = " from mall_product where isMarketable = true and uid='" + uid + "' ";

        if (StrKit.notBlank(keyword)) {
            sqlExceptSelect += " and name like '%" + keyword + "%'";
        }

        if (StrKit.notBlank(orderBy) && StrKit.notBlank(orderType.name())) {
            sqlExceptSelect += " order by " + orderBy + " " + orderType;
        }

        Page<Product> pager = dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
        return pager;
    }

    /**
     * 根据分页对象搜索产品
     *
     * @return 分页对象
     */
    public Page<Product> categorySearch(int pageNumber, int pageSize, ProductCategory productCategory, String orderBy, BaseController.OrderType orderType) {
        String select = "select p.* ";
        String sqlExceptSelect = ""
                + "  from mall_product p "
                + " inner join mall_product_category c "
                + "   on p.productcategory_id = c.id "
                + " where (p.productcategory_id = ? or c.path like ?) "
                + "  and p.ismarketable = ? and p.display=1";

        if (StrKit.notBlank(orderBy) && StrKit.notBlank(orderType.name())) {
            sqlExceptSelect += " order by " + orderBy + " " + orderType;
        }
        Page<Product> pager = dao.paginate(pageNumber, pageSize, select, sqlExceptSelect, productCategory.getStr("id"), productCategory.getStr("path") + "%", true);
        return pager;
    }

    /**
     * 根据分页对象搜索商户产品
     *
     * @return 分页对象
     */
    public Page<Product> businessCategorySearch(String uid, int pageNumber, int pageSize, ProductCategory productCategory, String orderBy, BaseController.OrderType orderType) {
        String select = "select p.* ";
        String sqlExceptSelect = ""
                + "  from mall_product p "
                + " inner join productcategory c "
                + "   on p.productcategory_id = c.id "
                + " where (p.productcategory_id = ? or c.path like ?) "
                + "  and p.ismarketable = ? and p.uid=?";

        if (StrKit.notBlank(orderBy) && StrKit.notBlank(orderType.name())) {
            sqlExceptSelect += " order by " + orderBy + " " + orderType;
        }
        Page<Product> pager = dao.paginate(pageNumber, pageSize, select, sqlExceptSelect, productCategory.getStr("id"), productCategory.getStr("path") + "%", true, uid);
        return pager;
    }

    /**
     * 根据Member、Pager获取收藏商品分页对象
     *
     * @param member Member对象
     * @return 收藏商品分页对象
     */
    public Page<Product> getFavoriteProductPager(Member member, int pageSize) {
        String select = "SELECT p.*,mp.favoriteMemberSet_id ";
        String sqlExceptSelect = ""
                + "  from mall_product p"
                + " inner join member_product mp"
                + "   on p.id = mp.favoriteproductset_id"
                + " inner join member m"
                + "   on mp.favoritememberset_id = m.id"
                + " where m.id = ?"
                + " order by p.name desc, p.createdate desc";

        Page<Product> list = dao.paginate(1, pageSize, select, sqlExceptSelect, member.getStr("id"));
        return list;
    }


    // 重写方法，保存对象的同时处理价格精度并生成HTML静态文件
    public void save(Product product) {
        HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.PRODUCT_CONTENT);
        String htmlFilePath = htmlConfig.getHtmlFilePath();
        product.set("id", CommonUtil.getUUID());
        product.set("htmlFilePath", htmlFilePath);
        product.set("createDate", new Date());
        product.save();
    }

    //重写方法，保存对象的同时处理价格精度并生成HTML静态文件(商户)
    public void save(Product product, String uid, String type, String userId) {
        product.set("uid", uid);
        product.setCreator(userId);
        if (type.equalsIgnoreCase("save")) {
            HtmlConfig htmlConfig = TemplateConfigUtil.getBusinessHtmlConfig(HtmlConfig.PRODUCT_CONTENT);
            String htmlFilePath = htmlConfig.getBusinessHtmlFilePath();
            String shopAlias = SiteConfig.getByShopId(uid).getStr("shopAlias");//获取店铺别名
            product.set("htmlFilePath", "/shop/" + shopAlias + htmlFilePath);
            product.set("createDate", new Date());
            if (StrKit.isBlank(product.getStr("productSn"))) {
                product.set("productSn", SerialNumberUtil.buildProductSn());
            }
            product.setId(StrKit.getRandomUUID());
            product.setModifyDate(new Date());
            product.save();
        } else {
            if (StrKit.isBlank(product.getStr("productSn"))) {
                product.set("productSn", SerialNumberUtil.buildProductSn());
            }
            product.set("modifyDate", new Date());
            product.update();
        }
    }

    // get产品分类
    public ProductCategory getProductCategory() {
        return ProductCategory.dao.findById(getStr("productCategory_id"));
    }

    // get 品牌
    public Brand getBrand() {
        return Brand.dao.findById(getStr("brand_id"));
    }

    // 产品类型
    public ProductType getProductType() {
        return ProductType.dao.findById(getStr("productType_id"));
    }

    /**
     * 根据SN判断数据是否已存在.
     *
     */
	/*public boolean isExist(String productSn){
		return dao.findFirst("select * from mall_product t where t.productSn = ?",productSn) != null;
	}*/

    /**
     * 根据SN判断数据是否已存在.
     */
    public boolean isExistProductSn(Product product) {
        if (StrKit.notBlank(product.getSpecificationtype())) {
            return dao.findFirst("select * from mall_product t where t.productSn = ? and specificationtype!=?", product.getProductSn(), product.getSpecificationtype()) != null;
        } else {
            return dao.findFirst("select * from mall_product t where t.productSn = ? and t.id !=?", product.getProductSn(), product.getId()) != null;
        }

    }

    /**
     * 根据SN判断数据是否已存在.
     */
    public boolean isExist2(String productSn, String specificationtype, String shopId) {
        if (StrKit.notBlank(specificationtype)) {
            return dao.findFirst("select * from mall_product t where t.productSn = ? and t.uid=? and specificationtype!=?", productSn, specificationtype, shopId) != null;
        } else {
            return dao.findFirst("select * from mall_product t where t.productSn = ? and t.uid=?", productSn, shopId) != null;
        }

    }


    /**
     * 根据最大返回数获取最新商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 最新商品集合
     */
    public List<Product> getNewProductList(int maxResults) {
        String sql = "select *  from mall_product  where isMarketable = ? and isNew = ? order by createDate desc limit 0,?";
        return dao.find(sql, true, true, maxResults);
    }


    /**
     * 根据最大返回数获取当前商户最新商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 最新商品集合
     */
    public List<Product> getBusinessNewProductList(String uid, int maxResults) {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.isNew = ? and p.uid=? and p.display=1 and p.checked='1' and b.isDisable='0' order by p.createDate desc limit 0,?";
        return dao.find(sql, true, true, uid, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取此分类下的最新商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的最新商品集合
     */
    public List<Product> getNewProductList(String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product t"
                + " where t.ismarketable = ?"
                + "   and t.isnew = ?"
                + "   and t.productcategory_id = ?"
                + " order by t.createdate desc limit 0, ?";
        return dao.find(sql, true, true, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取此分类下的最新商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的最新商品集合
     */
    public List<Product> getPlatformNewProductList(String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product p left join mall_business b on p.uid=b.shopId"
                + " where p.ismarketable = ?"
                + "   and p.isnew = ?"
                + "   and p.display = ?"
                + "   and p.productcategory_id = ?"
                + "   and p.checked='1' and b.isDisable='0'"
                + " order by p.createdate desc limit 0, ?";
        return dao.find(sql, true, true, true, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取当前商户此分类下的最新商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的最新商品集合
     */
    public List<Product> getBusinessNewProductList(String uid, String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product p left join mall_business b on p.uid=b.shopId"
                + " where p.ismarketable = ?"
                + "   and p.isnew = ?"
                + "   and p.display = ?"
                + "   and p.uid = ?"
                + "   and p.productcategory_id = ? "
                + "   and p.checked='1' and b.isDisable='0'"
                + " order by p.createdate desc limit 0, ?";
        return dao.find(sql, true, true, true, uid, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取当前商户此分类下的优惠商品(只包含isCheap=true的对象，包含子分类商品)
     *
     * @param maxResults 最大返回数
     * @return 此分类下的最新商品集合
     */
    public List<Product> getPlatformCheapProductList(int maxResults) {
        String sql = ""
                + "select p.*"
                + "  from mall_product p left join mall_business b on p.uid=b.shopId"
                + "  where p.ismarketable = ?"
                + "  and p.isCheap = ?"
                + "  and p.display = ?"
                + "  and p.checked='1'"
                + "  and p.isCheapPlateform='1' and b.isDisable='0'"
                + "  order by p.sortCheapPlateform,p.createDate desc limit 0, ?";
        return dao.find(sql, true, true, true, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取当前商户此分类下的优惠商品(只包含isCheap=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的最新商品集合
     */
    public List<Product> getBusinessCheapProductList(String uid, String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product t"
                + " where t.ismarketable = ?"
                + "   and t.isCheap = ?"
                + "   and t.display = ?"
                + "   and t.uid = ?"
                + " order by t.modifyDate desc,t.createDate desc limit 0, ?";
        return dao.find(sql, true, true, true, uid, maxResults);
    }

    /**
     * 根据最大返回数获取所有热卖商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 所有热卖商品集合
     */
    public List<Product> getHotProductList(int maxResults) {
        String sql = "select *  from mall_product  where isMarketable = ? and isHot = ? order by createDate desc limit 0,?";
        return dao.find(sql, true, true, maxResults);
    }


    /**
     * 根据最大返回数获取当前商户所有热卖商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 所有热卖商品集合
     */
    public List<Product> getBusinessHotProductList(String uid, int maxResults) {
        String sql = "select p.*  from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.isHot = ? and p.uid=? and p.display=1 and p.checked='1' and b.isDisable='0' order by p.createDate desc limit 0,?";
        return dao.find(sql, true, true, uid, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取此分类下的所有热卖商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的所有热卖商品集合
     */
    public List<Product> getHotProductList(String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product t"
                + "  where t.ismarketable = ?"
                + "  and t.ishot = ?"
                + "  and t.productcategory_id = ?"
                + "  order by t.createdate desc limit 0, ?";

        return dao.find(sql, true, true, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取此分类下的所有热卖商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的所有热卖商品集合
     */
    public List<Product> getPlatformHotProductList(String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product p left join mall_business b on p.uid=b.shopId"
                + " where p.ismarketable = ?"
                + "   and p.ishot = ?"
                + "   and p.productcategory_id = ?"
                + "   and p.checked='1' and b.isDisable='0'"
                + " order by p.createdate desc limit 0, ?";

        return dao.find(sql, true, true, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取当前商户此分类下的所有热卖商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的所有热卖商品集合
     */
    public List<Product> getBusinessHotProductList(String uid, String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product p left join mall_business b on p.uid=b.shopId"
                + " where p.ismarketable = ?"
                + "   and p.ishot = ?"
                + "   and p.display = ?"
                + "   and p.uid = ?"
                + "   and p.productcategory_id = ? "
                + "   and p.checked='1' and b.isDisable='0'"
                + " order by p.sortNo desc limit 0, ?";

        return dao.find(sql, true, true, true, uid, productCategory_id, maxResults);
    }

    /**
     * 根据最大返回数获取所有精品商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 所有精品商品集合
     */
    public List<Product> getBestProductList(int maxResults) {
        String sql = "select *  from mall_product  where isMarketable = ? and isBest = ? order by createDate desc limit 0,?";
        return dao.find(sql, true, true, maxResults);
    }

    /**
     * 根据最大返回数获取所有精品商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 所有精品商品集合
     */
    public List<Product> getPlatformBestProductList(int maxResults) {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.isBest = ? and p.checked='1' and p.isBestPlateform='1' and p.display=1 and b.isDisable='0' order by p.sortBestPlateform,p.createDate  limit 0,?";
        return dao.find(sql, true, true, maxResults);
    }

    /**
     * 获取所有精品商品(只包含isMarketable=true的对象，不限分类)
     *
     * @return 所有精品商品集合
     */
    public List<Product> getPlatformBestProductList() {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.isBest = ? and p.checked='1' and p.isBestPlateform='1' and p.display=1 and b.isDisable='0' order by p.sortBestPlateform,p.createDate";
        return dao.find(sql, true, true);
    }

    /**
     * 根据最大返回数获取最新商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 最新商品集合
     */
    public List<Product> getPlatformNewProductList(int maxResults) {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.checked='1' and p.isNewPlateform='1' and b.isDisable='0' order by createDate desc limit 0,?";
        return dao.find(sql, true, maxResults);
    }

    /**
     * 获取所有最新商品(只包含isMarketable=true的对象，不限分类)
     *
     * @return 最新商品集合
     */
    public List<Product> getPlatformNewProductList() {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.checked='1' and p.isNewPlateform='1' and b.isDisable='0' order by createDate desc";
        return dao.find(sql, true);
    }

    /**
     * 根据最大返回数获取所有热卖商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 所有热卖商品集合
     */
    public List<Product> getPlatformHotProductList(int maxResults) {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId  where p.isMarketable = ? and p.checked='1' and p.isHotPlateform='1' and b.isDisable='0' order by p.createDate desc limit 0,?";
        return dao.find(sql, true, maxResults);
    }

    /**
     * 获取所有热卖商品(只包含isMarketable=true的对象，不限分类)
     *
     * @return 所有热卖商品集合
     */
    public List<Product> getPlatformHotProductList() {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId  where p.isMarketable = ? and p.checked='1' and p.isHotPlateform='1' and b.isDisable='0' order by p.createDate desc";
        return dao.find(sql, true);
    }

    /**
     * 根据最大返回数获取所有热卖商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param maxResults 最大返回数
     * @return 所有今日推荐商品集合
     */
    public List<Product> getPlatformRecommendProductList(int maxResults) {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId  where p.isMarketable = ? and p.isTodayRecommend = ? and p.checked='1' and b.isDisable='0' order by p.createDate desc limit 0,?";
        return dao.find(sql, true, true, maxResults);
    }

    /**
     * 根据最大返回数获取所有当前商户精品商品(只包含isMarketable=true的对象，不限分类)
     *
     * @param uid        商户id
     * @param maxResults 最大返回数
     * @return 所有精品商品集合
     */
    public List<Product> getBusinessBestProductList(String uid, int maxResults) {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.isBest = ? and p.uid=? and p.display=1 and p.checked='1' and b.isDisable='0' order by p.sortNo limit 0,?";
        return dao.find(sql, true, true, uid, maxResults);
    }

    /**
     * 获取商户特惠商品
     *
     * @param shopId
     * @return
     */
    public List<Product> getCheapProductList(String shopId) {
        String sql = "select *  from mall_product  where isMarketable = ? and isBest = ? and uid=? and display=1 order by sortNo desc";
        return dao.find(sql, true, true, shopId);
    }

    /**
     * 获取所有商户特惠商品
     *
     * @return
     */
    public List<Product> getCheapProductListAll() {
        String sql = "select p.* from mall_product p left join mall_business b on p.uid=b.shopId where p.isMarketable = ? and p.isBest = ?  and p.display=? and p.checked='1' and b.isDisable='0' order by sortCheapPlateform,createDate desc";
        return dao.find(sql, true, true, true);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取此分类下的所有精品商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的所有精品商品集合
     */
    public List<Product> getBestProductList(String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product t"
                + " where t.ismarketable = ?"
                + "   and t.isbest = ?"
                + "   and t.productcategory_id = ?"
                + " order by t.createdate desc limit 0, ?";
        return dao.find(sql, true, true, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取平台此分类下的所有精品商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的所有精品商品集合
     */
    public List<Product> getPlatformBestProductList(String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + " from mall_product p left join mall_business b on p.uid=b.shopId"
                + " where p.ismarketable = ?"
                + " and p.isbest = ?"
                + " and p.productcategory_id = ?"
                + " and p.checked='1' and b.isDisable='0'"
                + " order by p.createdate desc limit 0, ?";
        return dao.find(sql, true, true, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象和最大返回数获取当前商户此分类下的所有精品商品(只包含isMarketable=true的对象，包含子分类商品)
     *
     * @param productCategory_id 商品分类
     * @param maxResults         最大返回数
     * @return 此分类下的所有精品商品集合
     */
    public List<Product> getBusinessBestProductList(String uid, String productCategory_id, int maxResults) {
        String sql = ""
                + "select *"
                + "  from mall_product p left join mall_business b on p.uid=b.shopId"
                + " where p.ismarketable = ?"
                + "   and p.isbest = ?"
                + "   and p.display = ?"
                + "   and p.uid = ?"
                + "   and p.productcategory_id = ?"
                + "   and p.checked='1' and b.isDisable='0'"
                + " order by p.createdate desc limit 0, ?";
        List<Product> list = dao.find(sql, true, true, true, uid, productCategory_id, maxResults);
		/*List<String> ids = new ArrayList<>();
		for (Product product : list) {
			if (!product.getIsShowSku()) {
				if (ids.contains(product.getId())) {
					list.remove(product);
				}
			}
			ids.add(product.getId());
		}*/
        return dao.find(sql, true, true, true, uid, productCategory_id, maxResults);
    }

    /**
     * 根据ProductCategory对象，获取此分类下的所有商品（只包含isMarketable=true的对象，包含子分类商品）
     *
     * @param productCategory 商品分类
     * @return 此分类下的所有商品集合
     */
    public List<Product> getProductList(ProductCategory productCategory) {
        String sql = "select * from  product where isMarketable = ? and productCategory_id =? order by createDate desc";
        return dao.find(sql, true, productCategory.getStr("id"));
    }

    /**
     * 根据ProductCategory对象、起始结果数、最大结果数，获取此分类下的所有商品（只包含isMarketable=true的对象，包含子分类商品）
     *
     * @param productCategory 商品分类
     * @param firstResult     起始结果数
     * @param maxResults      最大结果数
     * @return 此分类下的所有商品集合
     */
    public List<Product> getProductList(ProductCategory productCategory, int firstResult, int maxResults) {
        String sql = ""
                + "select p.*"
                + "  from mall_product p, productcategory pc "
                + " where p.productcategory_id = pc.id "
                + "   and p.ismarketable = ? "
                + "   and (pc.path like ?) "
                + " order by p.createdate desc limit ?,?";

        return dao.find(sql, true, productCategory.getStr("path") + "%", firstResult, maxResults);
    }

    /**
     * 根据起始结果数、最大结果数，获取所有商品（只包含isMarketable=true的对象）
     *
     * @param firstResult 起始结果数
     * @param maxResults  最大结果数
     * @return 此分类下的所有商品集合
     */
    public List<Product> getProductList(int firstResult, int maxResults) {
        String sql = "select *  from mall_product where isMarketable = ? order by createDate desc limit ?,?";
        return dao.find(sql, true, firstResult, maxResults);
    }

    /**
     * 根据起始日期、结束日期、起始结果数、最大结果数，获取商品集合（只包含isMarketable=true的对象）
     *
     * @param beginDate   起始日期，为null则不限制起始日期
     * @param endDate     结束日期，为null则不限制结束日期
     * @param firstResult 起始结果数
     * @param maxResults  最大结果数
     * @return 此分类下的所有商品集合
     */
    public List<Product> getProductList(Date beginDate, Date endDate, int firstResult, int maxResults) {
        if (beginDate != null && endDate == null) {
            String sql = "select *  from mall_product where isMarketable = ? and createDate > ? order by createDate desc limit ?,?";
            return dao.find(sql, true, beginDate, firstResult, maxResults);
        } else if (endDate != null && beginDate == null) {
            String sql = "select *  from mall_product  where isMarketable = ? and createDate < ? order by createDate desc limit ?,?";
            return dao.find(sql, true, endDate, firstResult, maxResults);
        } else if (endDate != null && beginDate != null) {
            String sql = "select *  from mall_product where isMarketable = ? and createDate > ? and createDate < ? order by createDate desc limit ?,?";
            return dao.find(sql, true, beginDate, endDate, firstResult, maxResults);
        } else {
            String sql = "select * from mall_product  where isMarketable = ? order by createDate desc limit ?,?";
            return dao.find(sql, true, firstResult, maxResults);
        }
    }

    public WeightUnit getWeightUnitValue() {
        return WeightUnit.values()[getInt("weightUnit")];
    }

    /**
     * 根据商品图片ID获取商品图片，未找到则返回null
     *
     * @param productImageId ProductImage对象
     */
    public ProductImage getProductImage(String productImageId) {
        List<ProductImage> productImageList = getProductImageList();
        for (ProductImage productImage : productImageList) {
            if (StringUtils.equals(productImageId, productImage.getId())) {
                return productImage;
            }
        }
        return null;
    }

    /**
     * 商品是否缺货
     */
    public boolean getIsOutOfStock() {
        if (getInt("store") != null && getInt("freezeStore") >= getInt("store")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取优惠价格，若member对象为null则返回原价格
     */
    public BigDecimal getPreferentialPrice(Member member) {
        if (member != null) {
            MemberRank memberRank = member.getMemberRank();
            if (memberRank != null) {
                BigDecimal preferentialPrice = getBigDecimal("price").multiply(new BigDecimal(memberRank.getPreferentialScale().toString()).divide(new BigDecimal("100")));
                return SystemConfigUtil.getPriceScaleBigDecimal(preferentialPrice);
            } else {
                return getBigDecimal("price");
            }

        } else {
            return getBigDecimal("price");
        }
    }

    /**
     * 获取商品图片
     *
     * @return
     */
    public List<ProductImage> getProductImageList() {
        String productImageListStore = getStr("productImageListStore");
        if (StringUtils.isEmpty(productImageListStore)) {
            return null;
        }
        List<ProductImage> list = JSON.parseArray(productImageListStore, ProductImage.class);
        return list;
    }

    /**
     * 设置商品图片
     *
     * @param productImageList
     */
    public void setProductImageList(List<ProductImage> productImageList) {
        if (productImageList == null || productImageList.size() == 0) {
            set("productImageListStore", null);
            return;
        }
        String jsonText = JSON.toJSONString(productImageList, true);
        set("productImageListStore", jsonText);
    }

    public String getAttributeType() {
        Product product = Product.dao.findFirst("");

        return "";
        //return OrderStatus.values()[getInt("orderStatus")];
    }

    /**
     * 获取属性
     *
     * @return
     */
    public Map<String, String> getProductAttributeMap() {
        String sql = "select * from mall_product_attribute_mapstore where product_id = ?";
        List<ProductAttributeMapstore> productAttributeList = ProductAttributeMapstore.dao.find(sql, getStr("id"));

        if (productAttributeList != null && productAttributeList.size() > 0) {
            for (ProductAttributeMapstore productAttribute : productAttributeList) {
                productAttributeMapStore.put(productAttribute.getStr("mapkey_id"), productAttribute.getStr("element"));
            }
        }
        return productAttributeMapStore;
    }

    public void setProductAttributeMap(Map<String, String> productAttributeMap) {
        this.setProductAttributeMap(productAttributeMap, null);
    }

    /**
     * 设置商品属性
     *
     * @param productAttributeMap
     */
    public void setProductAttributeMap(Map<String, String> productAttributeMap, String shopId) {
        if (productAttributeMap == null || productAttributeMap.size() == 0) {
            return;
        }
        // 先删除已存的
        Db.deleteById("mall_product_attribute_mapstore", "product_id", getStr("id"));
        ProductAttributeMapstore productAttribute = new ProductAttributeMapstore();
        for (Entry<String, String> entry : productAttributeMap.entrySet()) {
            productAttribute.set("product_id", getStr("id"));
            productAttribute.set("mapkey_id", entry.getKey());
            productAttribute.set("element", entry.getValue());
            if (StrKit.isBlank(shopId)) {
                shopId = "-1";
            }
            productAttribute.set("uid", shopId);
            productAttribute.save();
        }
    }

    /**
     * 收藏夹
     *
     * @return
     */
    public List<MemberProduct> getFavoriteMemberList() {
        String sql = "select * from mall_member_product where favoriteProductSet_id = ?";
        return MemberProduct.dao.find(sql, getStr("id"));
    }

    /**
     * 订单项
     *
     * @return
     */
    public List<OrderItem> getOrderItemList() {
        String sql = "select * from mall_order_item t where t.product_id = ?";
        return OrderItem.dao.find(sql, getStr("id"));
    }

    /**
     * 购物车项
     *
     * @return
     */
    public List<CartItem> getCartItemList() {
        String sql = "select * from mall_cart_item t where t.product_id = ?";
        return CartItem.dao.find(sql, getStr("id"));
    }

    /**
     * 物流项
     *
     * @return
     */
    public List<DeliveryItem> getDeliveryItemList() {
        String sql = "select * from mall_delivery_item t where t.product_id = ?";
        return DeliveryItem.dao.find(sql, getStr("id"));
    }

    /**
     * 商品属性存储
     *
     * @return
     */
    public List<ProductAttributeMapstore> getProductAttributeMapStore() {
        String sql = "select * from mall_product_attribute_mapstore t where t.product_id = ?";
        return ProductAttributeMapstore.dao.find(sql, getStr("id"));
    }

    /**
     * 获取商品库存报警数
     *
     * @return 商品库存报警数
     */
    public Long getStoreAlertCount() {
        String sql = "select count(*)  from mall_product  where isMarketable = ? and store - freezeStore <= ?";
        return Db.queryLong(sql, true, SystemConfigUtil.getSystemConfig().getStoreAlertCount());
    }

    /**
     * 获取已上架商品数
     *
     * @return 已上架商品数
     */
    public Long getMarketableProductCount() {
        String sql = "select count(*)  from mall_product  where isMarketable = ?";
        return Db.queryLong(sql, true);
    }

    /**
     * 获取已下架商品数
     *
     * @return 已下架商品数
     */
    public Long getUnMarketableProductCount() {
        String sql = "select count(*)  from mall_product  where isMarketable = ?";
        return Db.queryLong(sql, false);
    }

    /**
     * 关联处理
     *
     * @param product
     * @return
     */
    public boolean delete(Product product) {
        List<MemberProduct> favoriteMemberList = product.getFavoriteMemberList();
        if (favoriteMemberList != null && favoriteMemberList.size() > 0) {
            for (MemberProduct favoriteMember : favoriteMemberList) {
                favoriteMember.delete();
            }
        }
        List<OrderItem> orderItemList = product.getOrderItemList();
        if (orderItemList != null && orderItemList.size() > 0) {
            for (OrderItem orderItem : orderItemList) {
                orderItem.delete();
            }
        }
        List<DeliveryItem> deliveryItemList = product.getDeliveryItemList();
        if (deliveryItemList != null && deliveryItemList.size() > 0) {
            for (DeliveryItem deliveryItem : deliveryItemList) {
                deliveryItem.delete();
            }
        }

        List<CartItem> cartItemList = product.getCartItemList();
        if (cartItemList != null && cartItemList.size() > 0) {
            for (CartItem cartItem : cartItemList) {
                cartItem.delete();
            }
        }
        List<ProductImage> persistentProductImageList = product.getProductImageList();
        if (persistentProductImageList != null && persistentProductImageList.size() > 0) {
            for (ProductImage persistentProductImage : persistentProductImageList) {
                productImageService.deleteFile(persistentProductImage);
            }
        }
        // 先删除已存的
        Db.deleteById("mall_product_attribute_mapstore", "product_id", product.getStr("id"));
        return product.delete();
    }

    //根据字段类型排序获取某商户所有商品
    public List<Product> getByUid(String uid, String orderBy, String orderType) {
        return dao.find("select * from mall_product where uid=? and ismarketable=true order by " + orderBy + " " + orderType + " ", uid);
    }

    /**
     * 根据字段类型排序获取某商户所有商品(只展示display为1的)
     *
     * @param orderBy
     * @param orderType
     * @return
     */
    public List<Product> getAll(String orderBy, String orderType) {
        return dao.find("select p.* from mall_product p left join mall_business b on p.uid=b.shopId where  p.ismarketable=true and p.display=true and p.checked='1' and b.isDisable='0'  order by p." + orderBy + " " + orderType + " ");
    }

    /**
     * 根据字段类型排序获取某商户所有商品(只展示display为1的)
     *
     * @param shopId
     * @param orderBy
     * @param orderType
     * @return
     */
    public List<Product> getByShopId(String shopId, String orderBy, String orderType) {
        return dao.find("select * from mall_product where uid=? and ismarketable=true and display=true order by " + orderBy + " " + orderType + " ", shopId);
    }

    //按照关键字搜索商品列表
    public List<Product> getByKeyword(String uid, String orderBy, String orderType, String keyword) {
        return dao.find("select * from mall_product where uid=? and ismarketable=true and name like '%" + keyword + "%' order by " + orderBy + " " + orderType + " ", uid);
    }

    /**
     * 获取分类下的所有商品(包括子分类)
     *
     * @param productCategory
     * @param orderBy
     * @param orderType
     * @return
     */
    public List<Product> getRootProductCategory(ProductCategory productCategory, String orderBy, String orderType) {
        String sqlExceptSelect = ""
                + " select p.* from mall_product p "
                + " left join mall_product_category c "
                + "   on p.productcategory_id = c.id "
                + " where (p.productcategory_id = ? or c.path like ?) "
                + "  and p.ismarketable = ? and p.display=1 ";
        sqlExceptSelect += " order by " + orderBy + " " + orderType;
        return dao.find(sqlExceptSelect, productCategory.getStr("id"), productCategory.getStr("path") + "%", true);
    }

    /**
     * 获取分类下的所有商品(包括子分类)(wap页看了又看)
     *
     * @param productCategory
     * @param orderBy
     * @param orderType
     * @return
     */
    public List<Product> getRootProductCategory(ProductCategory productCategory, String orderBy, String orderType, Integer limit) {
        String sqlExceptSelect = ""
                + " select p.* from mall_product p "
                + " left join mall_product_category c "
                + "   on p.productcategory_id = c.id "
                + " where (p.productcategory_id = ? or c.path like ?) "
                + "  and p.ismarketable = ? and p.display=1 ";
        sqlExceptSelect += " order by " + orderBy + " " + orderType + " limit " + limit;
        return dao.find(sqlExceptSelect, productCategory.getStr("id"), productCategory.getStr("path") + "%", true);
    }

    public List<ProductGift> getProductGift() {
        return ProductGift.dao.find("select * from mall_product_gift where productId=?", getStr("id"));
    }

    public static Product getProductBySpecificationvalues(String specificationValueIds) {
        String[] idsArr = specificationValueIds.split(",");
        List<Object> paras = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select * from mall_product where 1=1 ");
        for (String s : idsArr) {
            sb.append(" and find_in_set(?, specificationvalues) ");
            paras.add(s);
        }
        sb.append(" limit 1");
        Product product = Product.dao.findFirst(sb.toString(), paras.toArray());
        return product;
    }

    public static Product getProductBySpecificationvalues(String specificationValueIds, String specificationType) {
        String[] idsArr = specificationValueIds.split(",");
        List<Object> paras = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select * from mall_product where 1=1 ");
        for (String s : idsArr) {
            sb.append(" and find_in_set(?, specificationvalues) ");
            paras.add(s);
        }
        sb.append(" and specificationtype=? ");
        paras.add(specificationType);
        sb.append(" limit 1");
        Product product = Product.dao.findFirst(sb.toString(), paras.toArray());
        return product;
    }

    public String getSpecificationValues() {
        String specificationValues = getSpecificationvalues();
        String values = "";
        if (StringUtils.isNotBlank(specificationValues)) {
            String[] valuesArr = specificationValues.split(",");
            for (String s : valuesArr) {
                SpecificationValue specificationValue = SpecificationValue.dao.findById(s);
                values += specificationValue.getName() + "  ";
            }
        }
        return values;
    }


    /**
     * 根据商品系列获取该商品下的所有商品
     *
     * @param specificationtype
     * @return
     */
    public List<Product> getBySpecificationTypeAndDisplay(String specificationtype, Integer display) {
        return dao.find("select * from mall_product where specificationtype=? and display=?", specificationtype, display);
    }

    /**
     * 根据商品系列获取该商品下的所有商品
     *
     * @param specificationtype
     * @return
     */
    public List<Product> getBySpecificationType(String specificationtype) {
        return dao.find("select * from mall_product where specificationtype=?", specificationtype);
    }

}
